package com.aigou.service;

import com.aigou.dao.BrandMapper;
import com.aigou.pojo.Brand;
import com.alibaba.fastjson2.JSON;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class BrandService {

    //Map<String, List<Brand>> cacheMap = new HashMap<>();
    java.util.concurrent.locks.ReentrantLock reentrantLock = new ReentrantLock();
    
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    
    @Autowired
    BrandMapper brandMapper;
    public List<Brand> findAll() {
    	
        // List<Brand> list = cacheMap.get("brandList");
    	List<Brand> list = null;
    	// 序列化  json 序列化
    	String brandListStr = stringRedisTemplate.opsForValue().get("brandList");
    	if (brandListStr != null) {
    		list = JSON.parseArray(brandListStr, Brand.class);
		}
        
        if (list == null) {
            reentrantLock.lock();
            //list = cacheMap.get("brandList");
            
            brandListStr = stringRedisTemplate.opsForValue().get("brandList");
        	if (brandListStr != null) {
        		list = JSON.parseArray(brandListStr, Brand.class);
    		}
            
            if (list == null) {
                //危险代码，只走一次
                list = brandMapper.selectByExample(null);
                
                // 转成json字符串
                //cacheMap.put("brandList", list);
                
                stringRedisTemplate.opsForValue().set("brandList", JSON.toJSONString(list));
            }
            reentrantLock.unlock();
        }
        return list;
    }
}
